#include "LogicPool/LogicQDCBoard.h"


void LogicQDCBoard::Init()
{
    int i;

    // open LogicPool Interface
    logicpool = new LogicInterfaceVME(handle, address);
    logicpool->Open();
    logicpool->Reset();
    uint8_t major, minor;
    logicpool->GetFirmwareVersion(major, minor);

    // create LogicPool objects
    for (i = 1; i <= 3; i++)
        qdc[i-1] =  new LogicQDC(*logicpool, i);
    for (i = 1; i <=8 ; i++) {
        dio[i-1] = new LogicDIO(*logicpool, i);
        led[i-1] = new LogicIndicator(*logicpool, i);
        log[i-1] = new LogicLogic(*logicpool, i);
    }
    for (i = 1; i <= 2; i++)
    counter[i-1] = new LogicCounter(*logicpool, i);

    // setup IO connectors
    for (i = 1; i <= 8; i++) {
        dio[i-1]->SetTermination(false);
        dio[i-1]->SetInput(0);  // reset input channel
    }
    for (i = 4; i <= 8; i++)
        dio[i-1]->SetNIM();

    // turn off all indicators
    for (i = 1; i <= 8; i++)
        LogicLow >> led[i-1];

    // start "wiring" ...

    LogicDIO & dio_gate   = *dio[3];        //  Gate input
    LogicDIO & dio_busy   = *dio[5];        //  Busy output

    // connect all triggers to the same dio
    dio_gate.SetTermination(false);
    dio_gate >> *qdc[0];
    dio_gate >> *qdc[1];
    dio_gate >> *qdc[2];
    dio_gate >> *led[3];

    // display single busy signal
    *qdc[0] >> *led[0];
    *qdc[1] >> *led[1];
    *qdc[2] >> *led[2];

    // generate busy signal
    // set all mode to "or"
    log[0]->SetMode(LogicLogic::MODE_OR);
    log[1]->SetMode(LogicLogic::MODE_OR);
    log[2]->SetMode(LogicLogic::MODE_OR);

    // log[0] = busy1 or busy2
    log[0]->Channel(0) << *qdc[0];
    log[0]->Channel(1) << *qdc[1];

    // log[1] = busy2 or busy3
    log[1]->Channel(0) << *qdc[1];
    log[1]->Channel(1) << *qdc[2];

    // *log[0] = *log[0] or log2
    log[0]->Channel(0) >> log[2]->Channel(0);
    log[2]->Channel(1) << log[1]->Channel(0);

    // combined busy signal on LED 5 and DIO 5
    dio_busy << *log[2]; 
    *led[5] << *log[2];

    // initialize the qdc modules
    for (i=0; i<3; i++) {
        qdc[i]->Init();
        qdc[i]->SetMode(1); //StopWertMessung
        //qdc[i]->SetMode(0); //DifferenzMessung
    }
}
